package io.github.ali.commons.bean;

import java.util.function.Function;

/**
 * @author ALi
 * @version 1.0
 * @date 2023-04-21 10:47
 * @description
 */
public class SystemParameter<T> extends Parameter<T> {
    private Function<String,T> valueGetter;
    protected SystemParameter(String name, T defaultValue) {
        super(name, defaultValue);
        //此时T应该是String
        this.valueGetter = (key) -> (T) System.getProperty(key);
    }
    protected SystemParameter(String name, T defaultValue, Function valueGetter) {
        super(name, defaultValue);
        this.valueGetter = valueGetter;
    }

    @Override
    public boolean doesExist() {
        return System.getProperty(name) != null;
    }

    @Override
    protected void save(T value) {
        System.setProperty(name, value.toString());
    }

    public void setValue(Function<String, String> source) {
        String value = source.apply(name);
        if (value != null) {
            System.setProperty(name, value);
        }
    }

    @Override
    public T getValue(T defaultValue) {
        T value = valueGetter.apply(name);
        return value == null ? defaultValue : value;
    }
}
